<script src="../../common/js/quill-config.js"></script>
<template>
  <section>

    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="success" @click="online">上线</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="offsale">下线</el-button>
        </el-form-item>

      </el-form>
    </el-col>

    <!--显示列表-->
    <el-table :data="pets" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>

      <el-table-column prop="name" label="名称" sortable>
      </el-table-column>
      <el-table-column prop="saleprice" label="销售价格" sortable>
      </el-table-column>
      <el-table-column prop="costprice" label="成本价" sortable>
      </el-table-column>

      <el-table-column prop="state" label="状态" sortable>
        <template slot-scope="scope">
          <span style="color: green" v-if="scope.row.state==1">上架</span>
          <span style="color: #ff0000" v-else="scope.row.state==-1">下架</span>
        </template>
      </el-table-column>

      <el-table-column prop="type.name" label="类型" sortable>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="shop.name" label="所属店铺" sortable>
      </el-table-column>
      <el-table-column prop="user.username" label="用户" sortable>
      </el-table-column>
      <el-table-column prop="searchMasterMsgId" label="宠物来源" sortable>
        <template slot-scope="scope">
          <span style="color: green" v-if="scope.row.searchMasterMsgId">寻主信息</span>
          <span style="color: #ff0000" v-else>店铺饲养</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <!-- 实现分页
      layout：布局
      @current-change：当前页发生变化调用的方法
      :current-page： 当前页
      :page-size：当前页显示条数
      total：数据总条数
      style ：风格
      -->
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :current-page="currentPage" :page-size="pageSize" :total="totals" style="float:right;">
      </el-pagination>
    </el-col>

    <!--添加和修改的对话框-->
    <!--
      :close-on-click-modal="false" - 点击对话外面的区域不关闭对话框
      :model="saveForm" - 绑定表单数据
      :rules="saveFormRules" - 校验规则
      ref="saveForm" - 对话框的名称 - 验证的时候需要用
      auto-complete="off" - 自动完成
    -->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">

        <!-- 如果要校验：必须加prop属性 -->
        <el-form-item label="名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="销售价格" prop="saleprice">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">上架</el-radio>
            <el-radio class="radio" :label="0">下架</el-radio>

          </el-radio-group>
        </el-form-item>
        <el-form-item label="资源" prop="resources">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/fastdfs"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>


        <el-form-item label="类型">
          <el-cascader v-model="saveForm.typeId"
                       :options="typesTerr"
                       :props="{ checkStrictly: true, label: 'name',value:'id'}"
                       clearable></el-cascader>

        </el-form-item>
        <el-form-item label="所属店铺" prop="shopId">
          <el-select v-model="saveForm.shopId" placeholder="请选择" clearable>
            <el-option v-for="item in shops"
                       :label="item.name"
                       :value="item.id">
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="简介" prop="intro">
          <quill-editor v-model="saveForm.petDetail.intro" v-if="saveForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="领养须知" prop="orderNotice" v-if="saveForm.petDetail" :options="quillOption">
          <quill-editor v-model="saveForm.petDetail.adoptNotice">
          </quill-editor>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>
<script>
//引入Vue的ueditor的资源
import {quillEditor} from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from "../../common/js/quill-config"

export default {
  data() {
    return {
      quillOption: quillConfig,
      //1.分页数据 - 要与模板中对应起来
      //分页查询 - 显示分页列表数据
      /* 数据展示的地方 */
      pets: [],
      //分页查询 - 总数量 - 计算分页栏
      totals: 0,
      //每页显示的条数
      pageSize: 5,
      //当前页 -  - 分页栏显示页数
      currentPage: 1,
      //分页列表是否显示
      listLoading: false,
      // 高级查询所需数据
      keyword: "",
      //批量删除 列表选中列
      sels: [],
      // 加载类型
      typesTerr: [],
      // 店铺
      shops: [],
      //用户
      users: [],
      typeId: null,
      //文件上传列表 - 资源resources
      fileList: [],
      petDetail: {  //与后端实体类一致
        intro: '',
        adoptNotice: '',
      },


      //添加或修改数据
      saveFormVisible: false,//添加或修改界面是否显示
      saveLoading: false,
      title: '',
      saveFormRules: {
        name: [
          {required: true, message: '请输入宠物名称', trigger: 'blur'}
        ],
        costprice: [
          {required: true, message: '请输入成本价', trigger: 'blur'}
        ],
        saleprice: [
          {required: true, message: '请输入销售价', trigger: 'blur'}
        ],
        shopId: [
          {required: true, message: '请选择所在店铺', trigger: 'blur'}
        ],
        type: [
          {required: true, message: '请选择宠物类型', trigger: 'blur'}
        ]
      },
      //编辑界面数据
      saveForm: {
        id: null,
        name: null,
        saleprice: "",
        costprice: "",
        resources: "",
        state: null,
        typeId: null,
        offsaletime: null,
        onsaletime: null,
        createtime: null,
        shopId: null,
        userId: null,
        searchMasterMsgId: "",
        auditnum: null,
        note: null,
        dirPath: [],
        petDetail: {  //与后端实体类一致
          intro: '',
          adoptNotice: '',
        }
      }
    }
  },
  methods: {
    //1.资源图片上传成功之后的处理
    handleSuccess(response, file, fileList) {
      console.log("=====图片上传成功的回调======")
      console.log(response);  //{ success: true, message: "操作成功", resultObj: "/group1/M00/02/1E/rBE3kWHL2xmANGvhAADIJRxVcQ896.jpeg" }

      //处理resources - 数据库操作
      if (this.saveForm.resources) { //有值  /group1/M00/00/72/rBEAA2BHkmaAbEOhAAEUusLjqqk505.png
        this.saveForm.resources = this.saveForm.resources + "," + response.resultObj;
      } else {
        this.saveForm.resources = response.resultObj;
      }

      //处理fileList - 页面回显的
      this.fileList = [];//清空
      if (this.saveForm.resources) {
        // /group1/M00/02/1B/rBE3kWHB-cCASterAACabDprSz419.jpeg,/group1/M00/02/1B/rBE3kWHB-caAQ3dYAABiwl7Ttcc206.jpg
        var resourcesArr = this.saveForm.resources.split(",");
        for (var i = 0; i < resourcesArr.length; i++) {
          this.fileList.push({url: "http://123.207.27.208" + resourcesArr[i]})
        }
      }
    },
    //2.资源图片点击删除时的处理
    handleRemove(file, fileList) {
      if (fileList == null || fileList.length == 0) {
        return;
      }
      console.log("=====图片删除的回调======")
      console.log(file)

      //删除fastDfs上的图片
      var filePath = file.url; // http://123.207.27.208/group1/M00/02/1E/rBE3kWHL_GWAAv5mAADpQr0XCJA99.jpeg
      //删除接口需要：/group1/M00/02/1E/rBE3kWHL_GWAAv5mAADpQr0XCJA99.jpeg
      var path = filePath.substring(filePath.indexOf("/group1")); // /group1/M00/02/1E/rBE3kWHL_GWAAv5mAADpQr0XCJA99.jpeg
      this.$http.delete("/fastDfs/?path=" + path).then(res => {
        if (res.data.success) {
          this.$message.success('删除成功!!!');
        } else {
          this.$message.error('删除失败!!!');
        }
      })

      // /group1/M00/02/1B/rBE3kWHB-cCASterAACabDprSz419.jpeg,/group1/M00/02/1E/rBE3kWHL_GWAAv5mAADpQr0XCJA99.jpeg,/group1/M00/02/1B/rBE3kWHB-caAQ3dYAABiwl7Ttcc206.jpg
      //处理resources - 数据库操作
      if (this.saveForm.resources) {
        //["/group1/M00/02/1B/rBE3kWHB-cCASterAACabDprSz419.jpeg","/group1/M00/02/1E/rBE3kWHL_GWAAv5mAADpQr0XCJA99.jpeg"]
        var pathArr = this.saveForm.resources.split(",");
        console.log(pathArr);
        for (var i = 0; i < pathArr.length; i++) {
          var pathTemp = pathArr[i];
          if (pathTemp == path) { //你要删除的图片找到了
            //从下标为i的地方开始删除，删1个
            pathArr.splice(i, 1);
            break;
          }
        }
        this.saveForm.resources = pathArr.join(",");
      }

      //处理fileList - 页面回显的
      this.fileList = [];//清空
      if (this.saveForm.resources) {
        // /group1/M00/02/1B/rBE3kWHB-cCASterAACabDprSz419.jpeg,/group1/M00/02/1B/rBE3kWHB-caAQ3dYAABiwl7Ttcc206.jpg
        var resourcesArr = this.saveForm.resources.split(",");
        for (var i = 0; i < resourcesArr.length; i++) {
          this.fileList.push({url: "http://123.207.27.208" + resourcesArr[i]})
        }
      }
    },
    // 获取店铺
    getShops() {
      this.$http.get("/shop").then(res => {
        this.shops = res.data;
      })
    },

    //获取类型树
    getTypeTerr() {
      this.$http.get("/petType/typeTerr").then(res => {
        this.typesTerr = res.data;
      })
    },

    // 获取类型数
    getType() {
      this.$http.get("/petType").then(res => {
        this.pettypes = res.data;
      })
    },

    // 关键字查询
    keywordQuery() {
      this.currentPage = 1;
      this.getpets();
    },

    //获取宠物列表
    getpets() {
      let para = {
        //当前页
        currentPage: this.currentPage,
        //每页显示的条数
        pageSize: this.pageSize,
        // 传递参数到后端
        keyword: this.keyword
      };


      //显示加载框/忙等框
      this.listLoading = true;
      this.$http.post("/pet", para).then(res => {
        //给totals赋值 - 计算分页栏
        this.totals = res.data.totals;
        //赋值分页数据 - 显示当前页的分页数据
        this.pets = res.data.data;
        //隐藏加载框/忙等框
        this.listLoading = false;
      }).catch(res => {
        alert("系统错误，请稍后重试!");
      });
    },
    //选项改变触发此方法(批量删除)：获取选中的对象
    selsChange: function (sels) {
      this.sels = sels;
    },

    // 分页换页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getpets();
    },

    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/pet/" + row.id).then(res => {
          this.listLoading = false;
          /*
           删除页最后一条 跳转 新一页
          success 成功运行*/
          if (res.data.success) {
            //计算总页数
            let totalPage = this.totals % this.pageSize == 0 ? this.totals / this.pageSize
                : Math.ceil(this.totals / this.pageSize);
            // 当前页>1 并且当前页是最后一页 并且 是最后一条数据
            if (this.currentPage > 1 && this.currentPage == totalPage && (this.totals - 1) % this.pageSize == 0) {
              // 当前页= 当前页-1
              // 跳转到新一页
              this.currentPage = this.currentPage - 1;
            }
            this.$message.success("操作成功");
            this.getpets();
          } else {
            this.$message.error("删除失败【500】");
          }
        }).catch(res => {
          this.$message.error("系统错误【400,404】");
        })
      }).catch(() => {
        //确认框点击取消之后走这里
      });
    },

    // 上线
    online() {
      //获取 id集合
      var ids = this.sels.map(item => item.id);
      console.log(ids);
      //获取选中的行
      if (!this.sels || this.sels.length < 1) {
        this.$message({message: '老铁，你不选中数据，臣妾上架不了啊....', type: 'error'});
        return;
      }
      this.$confirm('确认上架吗？', '提示', {
        type: 'warning'
      }).then(() => {//点击了确定
        this.$http.patch("/pet/online", ids).then(res => {
          this.listLoading = true;
          if (res.data.success) {
            this.$message.success("操作成功");
            this.getpets();
          } else {
            this.$message.error(res.data.message);
            this.listLoading = false;
            this.getpets();
          }
        }).catch(res => {
          this.$message.error("操作失败【400,404】")
        })
      })

    },
    //下架
    offsale() {
      var ids = this.sels.map(item => item.id);
      if (!ids || ids.length < 1) {
        this.$message.warning("请至少选择一条数据!!!");
        return;
      }
      this.$confirm('确认下架🐎？', '提示', {
        type: 'warning'
      }).then(() => {//点击了确定
        this.$http.patch("/pet/offsale", ids).then(res => {
          if (res.data.success) {
            this.$message.success("下架成功!!!");
            this.getpets();
          } else {
            this.$message.error("系统异常，请稍后重试!!!【500】");
          }
        }).catch(res => {
          this.$message.error("系统异常，请稍后重试!!!【400，404】");
        })
      }).catch(() => {//点了取消
      });
    },
    //批量删除
    batchRemove: function () {

      var ids = this.sels.map(item => item.id);
      console.log(ids);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;

        this.$http.patch("/pet", ids).then(res => {
          if (res.data.success) {
            //计算总页数
            let totalPage = this.totals % this.pageSize == 0 ? this.totals / this.pageSize
                : Math.ceil(this.totals / this.pageSize);
            // 当前页>1 并且当前页是最后一页 并且 是最后一条数据
            if (this.currentPage > 1 && this.currentPage == totalPage && (this.totals - 1) % this.pageSize == 0) {
              // 当前页= 当前页-1
              // 跳转到新一页
              this.currentPage = this.currentPage - 1;
            }
            this.$message.success("操作成功");

            this.getpets();
          } else {
            this.$message.error("操作失败【500】");
          }
          this.listLoading = false;
        }).catch((res) => {
          this.$message.error("操作失败【400,404】")
        })
        // 取消点击 确定框
      }).catch(() => {
      });
    },

    //点击编辑按钮弹出模态框
    handleEdit: function (index, row) {

      this.title = "修改";
      this.saveForm = Object.assign({}, row);

      //图片回显
      this.fileList = [];
      var resources = row.resources;
      if (resources) {
        var resourcesArr = resources.split(",");
        for (var i = 0; i < resourcesArr.length; i++) {
          this.fileList.push({url: "http://123.207.27.208" + resourcesArr[i]})
        }
      }


      this.getShops();
      this.getTypeTerr();
      this.saveFormVisible = true;
      //显示详情
      this.$http.get("/pet/detail/" + row.id).then(result => {
        this.saveForm.petDetail = result.data;
        //异步请求：先查询到数据在显示模态框 - 否则数据回显不了
        this.saveFormVisible = true;
      });
    },
//点击添加按钮弹出模态框
    handleAdd: function () {
      this.title = "添加";
      this.saveForm = {
        id: null,
        name: null,
        saleprice: "",
        costprice: "",
        resources: "",
        state: null,
        typeId: null,
        offsaletime: null,
        onsaletime: null,
        createtime: null,
        shopId: null,
        userId: null,
        searchMasterMsgId: null,
        auditnum: null,
        note: null,
        petType: null,
        petDetail: {  //与后端实体类一致
          intro: '',
          adoptNotice: ''
        }
      };


      //清空列表
      this.fileList = [];
      this.getShops();
      this.getTypeTerr();

      this.saveFormVisible = true;

    },
    //点击对话框提交数据
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            // 获取表单数据
            let paras = Object.assign({}, this.saveForm);

            //对父部门做处理
            //提交数据时上级部门数据格式做处理：[3,8] - {id:8}
            var arr = this.saveForm.typeId; //[ 3, 8 ]
            if (arr) {
              //防止400错误
              paras.typeId = arr[arr.length - 1]
            }

            //5.点击提交对dirPath的处理
            //提交数据时上级类型数据格式做处理：[3,8]
            var arr = this.saveForm.type; //[ 3, 8 ]
            if (arr) {
              //防止400错误
              paras.type = null;
              paras.typeId = arr[arr.length - 1]
            }

            this.$http.put("/pet", paras).then(res => {
              this.saveFormVisible = false;
              this.saveLoading = false;
              if (res.data.success) {
                this.getpets();
              } else {
                this.$message.error("操作失败【500】");
              }
            }).catch(res => {
              this.$message.error("系统错误【400,404】");
            })
          });
        }
      });
    },
  },


  // 页面加载就显示
  mounted() {
    this.getpets();
  },
  components: {
    quillEditor
  },
}

</script>

<style scoped>

</style>